package com.example.recall_application.mvp.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.SPUtils;
import com.example.recall_application.R;
import com.example.recall_application.app.Constants;
import com.example.recall_application.mvp.entity.WxUserInfo;
import com.example.recall_application.utils.FileUtils;
import com.example.recall_application.utils.ScreenManager;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.net.URI;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.view.KeyEvent.KEYCODE_BACK;

public class WebActivity extends AppCompatActivity {


    static String url = "http://wechat.nonlogin.com/admin/?m=srv&a=post_userinfo";
    @BindView(R.id.webview)
    WebView mWebView;
    @BindView(R.id.root)
    LinearLayout root;
    @BindView(R.id.iv)
    ImageView iv;
    long mExitTime;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    protected final String TAG = this.getClass().getSimpleName();
    PowerManager.WakeLock wakeLock;
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initData(savedInstanceState);
        //系统默认会通过手机浏览器打开网页，为了能够直接通过WebView显示网页，则必须设置
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                if (url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse(url));
                    startActivity(intent);
                    return true;
                }

                //使用WebView加载显示url
                view.loadUrl(url);
                //返回true
                return true;
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();

        if(TextUtils.isEmpty(SPUtils.getInstance().getString(Constants.uuid))){
            finish();
            return;
        }

        if (mWebView != null) {
            mWebView.onResume();
            //恢复pauseTimers状态
            mWebView.resumeTimers();

            if(!TextUtils.isEmpty(SPUtils.getInstance().getString(Constants.uuid))){
                mWebView.loadUrl(url);
            }

//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    FileUtils fileUtils = new FileUtils();
//                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/ HH:mm:ss");// HH:mm:ss
////获取当前时间
//                    Date date = new Date(System.currentTimeMillis());
//                    fileUtils.writeData(simpleDateFormat.format(date)+":--url"+url,"web_url.txt");
//                }
//            }).start();
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mWebView != null) {
            mWebView.onPause();
            //它会暂停所有webview的layout，parsing，javascripttimer。降低CPU功耗
            mWebView.pauseTimers();
        }
    }



    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public void initData(@Nullable Bundle savedInstanceState) {


        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        //支持插件

        // webSettings.setPluginsEnabled(true);
        webSettings.setMediaPlaybackRequiresUserGesture(true);

        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小

        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小


        //缩放操作

        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。

        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放

        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件


        //其他细节操作

        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //关闭webview中缓存

        webSettings.setAllowFileAccess(true); //设置可以访问文件

        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口

        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片

        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if ((keyCode == KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        else {
//            if ((System.currentTimeMillis() - mExitTime) > 2000) {
//                Toast.makeText(this, "再按一次退出APP", Toast.LENGTH_SHORT).show();
//                //System.currentTimeMillis()系统当前时间
//                mExitTime = System.currentTimeMillis();
//            } else {
                Intent intent = new Intent(Intent.ACTION_MAIN);

                intent.addCategory(Intent.CATEGORY_HOME);

                startActivity(intent);
           // }
            return true;
        }
        // return super.onKeyDown(keyCode, event);
    }

    @Subscriber(mode = ThreadMode.MAIN)
    public void getWxUserInfo(WxUserInfo wxUserInfo) {
        mWebView.clearCache(true);
        deleteDatabase("webview.db");
       deleteDatabase("webviewCache.db");
       String nickName = wxUserInfo.getNickname();


        url = url + "&sex=0" + wxUserInfo.getSex() + "&city=" + wxUserInfo.getCity()
                + "&country=" + wxUserInfo.getCountry()
                + "&unionid=" + SPUtils.getInstance().getString(Constants.uuid)
                + "&nickname=" + Uri.encode(nickName)
                + "&province=" + wxUserInfo.getProvince()
                + "&privilege=" + wxUserInfo.getPrivilege()
                + "&headimgurl=" + wxUserInfo.getHeadimgurl();
        mWebView.loadUrl(url);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        root.removeView(mWebView);
        mWebView.destroy();
        EventBus.getDefault().unregister(this);

    }


    @OnClick({R.id.iv_back, R.id.iv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                if ( mWebView.canGoBack()) {
                    mWebView.goBack();
               }
//                else {
//                    if ((System.currentTimeMillis() - mExitTime) > 2000) {
//                        Toast.makeText(this, "再按一次退出APP", Toast.LENGTH_SHORT).show();
//                        //System.currentTimeMillis()系统当前时间
//                        mExitTime = System.currentTimeMillis();
                   // }
                else {
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        startActivity(intent);
                    }
                //}
                break;
            case R.id.iv:
                Intent intent = new Intent(this, ConfigActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Subscriber(mode = ThreadMode.MAIN)
    public void kill(String flag){
        if(flag.equals(Constants.KILL)){
            onDestroy();
        }
    }
}
